#include "Timer.h"
#include "Logger.h"

using namespace devem;

int Timer::CreateTimerFd() {
    /*
    int timerfd_create(int clockid, int flags);

    int timerfd_settime(int fd, int flags,
                           const struct itimerspec *new_value,
                           struct itimerspec *old_value);

    int timerfd_gettime(int fd, struct itimerspec *curr_value);

    clockid:
    1. CLOCK_REALTIME
        A settable system‐wide real‐time clock.

    2. CLOCK_MONOTONIC
        A  nonsettable  monotonically increasing clock that measures time from
        some unspecified point in the past that does not change
              after system startup.

    struct itimerspec {
        struct timespec  it_interval;  // Interval for periodic timer
        struct timespec  it_value;     // Initial expiration
    };

    struct timespec {
        time_t  tv_sec;   // Seconds
        long    tv_usec;  // Nanoseconds [0, 999999999]
    };

    read:定时器会在每次超时时，自动给fd中写入8字节的数据，表示在上次读取数据到当前读取数据期间超时了多少次

    */

    int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
    if (timerfd < 0) {
        return -1;
    }

    struct itimerspec itime;
    itime.it_value.tv_sec = 1;
    itime.it_value.tv_nsec = 0;  // 第一次超时时间为1s后
    itime.it_interval.tv_sec = 1;
    itime.it_interval.tv_nsec = 0;  // 第一次超时后，每次超时的间隔时
    timerfd_settime(timerfd, 0, &itime, NULL);
    return timerfd;
}
